<?php 
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\Db;
use think\Validate;
use app\admin\model\ContractModel;
use app\admin\model\AccessModel;
use app\admin\model\AdminMenuModel;

/**
* 公司用户列表
*/
class CompanyUserController extends AdminBaseController
{

	private $pageNum = 30;

	/**
	 * 用户列表
	 */
	public function index()
	{
		$param = $this->request->param();
		$cid = $param['cid'];

		$uid = Db::name( 'user_attach' )->where( 'company_id' , $cid )->column('user_id');
		$userList = Db::name('user')->where( 'id' , 'IN' , $uid )->field('id,user_login')->paginate($this->pageNum);

		$role = $this->getHeightRole( $cid );
		$spUid = Db::name('user_attach')->where('role_id',$role['id'])->column('user_id');
		$this->assign( 'spUid' , $spUid );
		$this->assign('userList' , $userList );
		return $this->fetch( 'company/company_user/index' );
	}
	
	
	public function resetpwd($uid)
	{
		$this->assign( 'uid' , $uid );
		return $this->fetch('company/company_user/resetpwd');
	}
	
	public function pwdPost()
	{
		$param = $this->request->param();
		$uid = $param ['uid'];
		$pwd = $param [ 'pwd' ];
		$repwd = $param [ 'repwd' ];
		if( empty( $pwd ) || empty( $repwd ) ){
			return zy_json_echo(false , '请填写密码！');
		}
		if( $pwd != $repwd ){
			return zy_json_echo(false, '两次输入密码不同！');
		}
		$newpwd = cmf_password($pwd);
		$res = Db::name('user')->where('id',$uid)->update(['user_pass'=>$newpwd]);
		if( !$res ){
			return zy_json_echo(false,'密码修改失败，请稍候再试！');
		}
		return zy_json_echo(true,'密码修改成功！');
	}

	/**
	 * 获取公司的最高角色信息
	 */
	
	private function getHeightRole( $companyId )
	{
		$role = null;
		$list = Db::name('role')->where('company_id',$companyId)->select()->toArray();
		foreach ($list as $key => $value) {
			$find = $this->getHigherUpRoleRecursion( $list , $value['parent_id']);
			if( $find != false ){
				$role = $value;
				break;
			}
		}
		return $role;
	}


	/**
	 * 递归查询
	 */
	private function getHigherUpRoleRecursion( $list , $roleId  )
	{

		foreach ($list as $key => $value) {
			if( $value ['id'] == $roleId ){
				$roleId = false;
				break;
			}
		}
		return $roleId;
	}
	
	
	
	
}